//
//  LoginViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/24.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

class LoginViewController: BaseViewController {

    @IBOutlet weak var closeBtnTop: NSLayoutConstraint!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var centerImageView: UIImageView!
    @IBOutlet weak var clearBtn: UIButton!
    
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var passWordField: UITextField!
    
    @IBOutlet weak var registerBtn: UIButton!
    
    @IBOutlet weak var forgetBtn: UIButton!
    
    
    var isShow = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.changeContent()
        self.phoneField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        self.passWordField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        if let phone = UserDefaults.standard.object(forKey: "userPhone")  {
            self.phoneField.text = (phone as! String)
            self.clearBtn.isHidden = false
        }
        self.passWordField.isSecureTextEntry = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UIView.animate(withDuration: 1) {
            self.contentView.alpha = 1
        }
    }
    
    
    @IBAction func closeBtnMethod(_ sender: UIButton) {
        (UIApplication.shared.delegate as! AppDelegate).isShowLogin = false
        self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func ClearPhoneMethod(_ sender: UIButton) {
        self.phoneField.text = ""
        self.phoneField.becomeFirstResponder()
        sender.isHidden = true
    }
    
    // MARK:登录
    @IBAction func loginMethod(_ sender: UIButton) {
        self.view.endEditing(true)
        
//        if self.phoneField.text?.count == 0 {
//            self.noticeOnlyText("请输入手机号")
//            return
//        }
        if self.phoneField.text?.count != 11  {
            PKhud.showText(text: "请输入正确的手机号~")
            self.phoneField.becomeFirstResponder()
            return
        }
        
        if self.passWordField.text?.count == 0 {
            PKhud.showText(text: "请输入密码~")
            self.passWordField.becomeFirstResponder()
            return
        }
        if (self.passWordField.text?.count)! < 6 {
            PKhud.showText(text: "密码强度过低，需至少6位~")
            self.passWordField.becomeFirstResponder()
            return
        }
        
        let parameter:postParameters = ["username":self.phoneField.text!,
                                        "password":self.passWordField.text!]
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.login.rawValue, parameters: parameter) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.hiden()
                let dic = result["data"] as! postParameters
                if let userDic = dic["user"] as? postParameters {
                    UserDefaults.standard.set(self.phoneField.text!, forKey: "userPhone")
                    UserDefaults.standard.set(dic["authorization"] as! String, forKey: "token")
                    SaveUserInfo.saveUserInfo(with: userDic)
                    UserDefaults.standard.synchronize()
                    (UIApplication.shared.delegate as! AppDelegate).isShowLogin = false
                }
                (UIApplication.shared.delegate as! AppDelegate).addClildCtrl()
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    /// 是否显示密码
    ///
    /// - Parameter sender:
    @IBAction func isShowPassWord(_ sender: UIButton) {
        
        if !self.isShow {
            self.passWordField.isSecureTextEntry = false
            sender.isSelected = false
        }else{
            self.passWordField.isSecureTextEntry = true
            sender.isSelected = true
        }
        self.isShow = !self.isShow
    }
    
    // MARK:注册账号
    @IBAction func registerMethod(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "RegisterTableViewController") as! RegisterTableViewController
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    
    // MARK:忘记密码
    @IBAction func forgetMethod(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ForgetPassWordTableViewController") as! ForgetPassWordTableViewController
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
}

extension LoginViewController {
    fileprivate func changeContent(){
        
        self.centerImageView.setCornerRadio(radio: 40, isMask: false)
        self.centerImageView.setShadow(color: "000000", offset: CGSize.init(width: 0, height: 5), radius: 5, opacity: 0.1)
        
        var attributedString = NSMutableAttributedString(string: "注册账号")
        attributedString.addAttributes([
            NSAttributedStringKey.underlineStyle:1,
            NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#333333")], range: NSRange(location: 0, length: 4))
        self.registerBtn.setAttributedTitle(attributedString, for: .normal)

        attributedString = NSMutableAttributedString(string: "忘记密码?")
        attributedString.addAttributes([
            NSAttributedStringKey.underlineStyle:1,
            NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#333333")], range: NSRange(location: 0, length: 4))
        self.forgetBtn.setAttributedTitle(attributedString, for: .normal)

        attributedString.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#333333")], range: NSRange(location: 4, length: 1))
        self.forgetBtn.setAttributedTitle(attributedString, for: .normal)
        
        self.phoneField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.passWordField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
    }
    
    @objc func valueChange(textField:UITextField){
        var maxLength = 0
        if textField == self.phoneField {
            maxLength = 11
            if textField.text?.count == 0 {
                self.clearBtn.isHidden = true
            }else{
                self.clearBtn.isHidden = false
            }
        }else{
            maxLength = 12
        }
        let toBeString = textField.text!
        let lang = textField.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            let selectedRange = textField.markedTextRange
            if selectedRange == nil && toBeString.count > maxLength{
                let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
                textField.text = String(toBeString[..<endIndex])
            }
        }else if toBeString.count > maxLength {
            let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
            textField.text = String(toBeString[..<endIndex])
        }
    }
}


struct SaveUserInfo {
    
    static func saveUserInfo(with dic:postParameters) {
        
        
        let dictionary:NSDictionary = dic as NSDictionary
        let keys:[String] = dictionary.allKeys as! [String]
        
        for (_,key) in keys.enumerated() {
            if let value = dictionary[key] {
                if !(value is NSNull) {
                    if value is String {
                        UserDefaults.standard.set(value, forKey: key)
                    }else{
                        UserDefaults.standard.set("\(value)", forKey: key)
                    }
                    
                }
            }
        }
    }
}

























